package com.tj.collection.controller.admin;

import com.alibaba.fastjson.JSON;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Page;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.MD5;
import com.fqgj.exception.common.ApplicationException;
import com.google.common.collect.Lists;
import com.qianli.cashmama.product.facade.result.ProductCategory;
import com.tj.collection.aop.anno.VisitorAccessible;
import com.tj.collection.application.AdminApplication;
import com.tj.collection.application.PermissionApplication;
import com.tj.collection.bean.ApiResponse;
import com.tj.collection.bean.RedisKey;
import com.tj.collection.common.RequestLocalInfo;
import com.tj.collection.controller.admin.request.*;
import com.tj.collection.controller.admin.response.*;
import com.tj.collection.db.admin.dao.AdminDAO;
import com.tj.collection.db.admin.dao.AuthAdminProductDao;
import com.tj.collection.db.admin.entity.AdminEntity;
import com.tj.collection.db.domain.Admin;
import com.tj.collection.db.domain.AdminAndRole;
import com.tj.collection.db.enums.RestErrorCodeEnum;
import com.tj.collection.db.enums.RoleKeyEnum;
import com.tj.collection.db.service.AdminRoleService;
import com.tj.collection.db.service.AdminService;
import com.tj.collection.enums.HostProductMappingEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/3/11
 * Time: 下午4:53
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private AdminService adminService;

    @Autowired
    private PermissionApplication permissionApplication;


    @Autowired
    private AuthAdminProductDao authAdminProductDao;

    @Autowired
    private AdminApplication adminApplication;

    @Autowired
    private AdminRoleService adminRoleService;

    @Autowired
    private AdminDAO adminDAO;

    /**
     * 注册超级管理员
     *
     * @param adminRegisterVO
     * @return
     */
    @RequestMapping("/register")
    @ParamsValidate
    public ApiResponse register(@RequestBody AdminRegisterVO adminRegisterVO) {
        adminService.registration(adminRegisterVO.transform2Admin());
        return new ApiResponse<>();
    }

    /**
     * 管理员登录
     *
     * @param adminLoginVO
     * @return
     */
    @RequestMapping("/login")
    @ParamsValidate
    public ApiResponse<LoginResponse> login(@RequestBody AdminLoginVO adminLoginVO) {
        String appClient = RequestLocalInfo.getRequestBasicInfo().getAppClient();
        Admin admin = adminService.getOneAdminByAccount(adminLoginVO.getAccount());
        if(admin==null){
            throw new ApplicationException("Wrong login info!");
        }
        if (StringUtils.isNotBlank(adminLoginVO.getPassword())) {
            admin.setPassword(adminLoginVO.getPassword());
        } else {
            throw new ApplicationException("Verification code is empty!");
        }

        String host = RequestLocalInfo.getRequestBasicInfo().getHost();
        String merchantCodeFilter = null;
        if (StringUtils.isNotEmpty(host) && "web".equals(RequestLocalInfo.getRequestBasicInfo().getAppClient())) {
            HostProductMappingEnum hostProductMappingEnum = HostProductMappingEnum.getEnumByHost(host);
            merchantCodeFilter = hostProductMappingEnum == null ? null : hostProductMappingEnum.getMerchantCode();
            logger.info("LMS查询,根据域名做产品过滤,host:{},merchantCodeFilter:{}", host, merchantCodeFilter);
        }

        String adminMerchantCode = admin.getMerchantCode();
        boolean isMultipleMerchant = adminRoleService.isContainsRoleKey(admin.getId(), RoleKeyEnum.MULTIPLE_MERCHANT, adminMerchantCode);
        if (!isMultipleMerchant) {
            //指定域名只能登录指定商户的用户
            if (merchantCodeFilter != null && !merchantCodeFilter.equals(adminMerchantCode)) {
                throw new ApplicationException("User does not exist");
            }
        }

        String token = adminApplication.login(admin, "web".equals(appClient));
        return new ApiResponse<>(new LoginResponse(admin.getName(), token));
    }

    /**
     * 账户信息获取
     *
     * @return
     */
    @RequestMapping("/security/info/get")
    @ParamsValidate
    public ApiResponse<AdminAccountInfoResponse> getAccount() {
        String account = RequestLocalInfo.getCurrentAdmin().getAccount();
        Admin admin = adminService.getOneAdminByAccount(account);
        return new ApiResponse<>(new AdminAccountInfoResponse(
                admin.getAccount(),
                admin.getName(),
                admin.getMobile(),
                admin.getMerchantCode()));
    }


    /**
     * 新增管理员
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ParamsValidate
    public ApiResponse addAdmin(@RequestBody AddAdminVo addAdminVo) {
        List<String> productCodeList = new ArrayList<>();
        adminService.add(addAdminVo.trans2Admin(), addAdminVo.getRoles(), addAdminVo.getProductCode(), productCodeList);
        return new ApiResponse();
    }

    /**
     * 查询管理员列表（管理员ID，登录名，中文名，角色，产品类型）
     *
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public ApiResponse<AdminListResponse> list(@RequestBody AddAdminVo addAdminVo, Page page) {
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        List<AdminAndRole> adminAndRoleList = adminService.searchAdmin(addAdminVo.getName(), addAdminVo.getFullName(), page, merchantCode);
        List<ProductCategory> productCategoryList = new ArrayList<>();
        return new ApiResponse<>(new AdminListResponse(adminAndRoleList, productCategoryList, page));
    }

    /**
     * 查询管理员列表
     *
     * @param adminQueryRequest
     * @return
     */
    @VisitorAccessible
    @RequestMapping("/account/list")
    public ApiResponse<AdminAccountResponse> getAccount(@RequestBody AdminQueryRequest adminQueryRequest) {
        if (StringUtils.isEmpty(adminQueryRequest.getMobile())) {
            throw new ApplicationException("phone number empty!");
        }
        List<AdminEntity> adminEntityList = adminDAO.getByMobile(adminQueryRequest.getMobile());
        return new ApiResponse<>(new AdminAccountResponse(adminEntityList));
    }


    /**
     * 获取闪电周转产品权限
     *
     * @return
     */
    @RequestMapping("/sdzzproduct/list")
    @ParamsValidate
    public ApiResponse<SdzzProductListResponse> sdzzProductList() {
        return new ApiResponse<>(new SdzzProductListResponse());
    }

    /**
     * 更新管理员信息
     *
     * @param adminId
     * @param addAdminVo
     * @return
     */
    @RequestMapping("/{adminId}/update")
    public ApiResponse update(@PathVariable Long adminId, @RequestBody AddAdminVo addAdminVo) {
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        List<ProductCategory> productCategoryList =new ArrayList<>();
        List<String> list = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList) {
            list.add(productCategory.getCode());
        }
        adminService.update(addAdminVo.trans2Admin().setId(adminId), list);
        return new ApiResponse<>();
    }

    /**
     * 修改密码
     *
     * @param updatePasswordRequest
     * @return
     */
    @RequestMapping("/password/update")
    public ApiResponse update(@RequestBody UpdatePasswordRequest updatePasswordRequest) {
        String account = RequestLocalInfo.getCurrentAdmin().getAccount();
        if (!account.equals(updatePasswordRequest.getAccount()) || StringUtils.isEmpty(updatePasswordRequest.getNewPassword())) {
            throw new ApplicationException(RestErrorCodeEnum.SYSTEM_PARAMTER_ERROR);
        }
        Admin admin = adminService.getOneAdminByAccount(account);
        if ("otp".equals(updatePasswordRequest.getVerificationMethod())) {
            String valueCode = redisClient.get(RedisKey.VERIFY_CODE_KEY + admin.getMobile());
            if (StringUtils.isNotEmpty(valueCode) && valueCode.equals(updatePasswordRequest.getVerifyCode())) {
                adminService.updateAdminPassword(admin.getId(), updatePasswordRequest.getNewPassword());
                logger.info("通过验证码设置新密码成功,updatePasswordRequest:{}", JSON.toJSONString(updatePasswordRequest));
            } else {
                throw new ApplicationException(RestErrorCodeEnum.SYSTEM_PARAMTER_ERROR);
            }
        } else {
            if (StringUtils.isNotEmpty(updatePasswordRequest.getPassword()) &&
                    (admin.getPassword().equals(updatePasswordRequest.getPassword()) || admin.getPassword().equals(MD5.md5(updatePasswordRequest.getPassword())))
            ) {
                adminService.updateAdminPassword(admin.getId(), updatePasswordRequest.getNewPassword());
                logger.info("通过旧密码修改新密码成功,updatePasswordRequest:{}", JSON.toJSONString(updatePasswordRequest));
            } else {
                throw new ApplicationException(RestErrorCodeEnum.SYSTEM_PARAMTER_ERROR);
            }
        }


        return new ApiResponse<>();
    }

    /**
     * 修改管理员状态
     *
     * @param adminStatusVo
     * @return
     */
    @RequestMapping("/{adminId}/updateadminstatus")
    public ApiResponse updateAdminStatus(@RequestBody AdminStatusVo adminStatusVo) {
        permissionApplication.updateAdminStatus(adminStatusVo.getAdminId(), RequestLocalInfo.getCurrentAdmin().getId(), adminStatusVo.getAdminStatus());
        return new ApiResponse<>();
    }

    /**
     * 删除管理员
     *
     * @param adminId
     * @return
     */
    @RequestMapping("/{adminId}/deleteadmin")
    public ApiResponse deleteAdmin(@PathVariable Long adminId) {
        logger.info("删除管理员,admin:{},adminId:{}", JSON.toJSONString(RequestLocalInfo.getCurrentAdmin()), adminId);
        permissionApplication.deleteAdmin(adminId, RequestLocalInfo.getCurrentAdmin().getId());
        return new ApiResponse<>();
    }

    /**
     * 根据管理员ID获取菜单ID
     *
     * @param adminId
     * @return
     */
    @RequestMapping("/{adminId}/ids")
    public ApiResponse adminMenuIds(@PathVariable Long adminId) {
        List<Long> adminMenuIds = adminService.getMenuIdsByAdminId(adminId);
        return new ApiResponse<>(new RoleMenuIdsResponse(adminMenuIds));
    }



    private List<ProductCategory> doProductFilter(List<ProductCategory> productCategoryList, List<String> productFilter) {
        if (CollectionUtils.isEmpty(productFilter)) {
            return productCategoryList;
        }
        List<ProductCategory> newList = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList) {
            if (productFilter.contains(productCategory.getCode())) {
                newList.add(productCategory);
            }
        }
        return newList;
    }

    /**
     * APP下拉列表
     *
     * @return
     */
    @RequestMapping("/app/list")
    public ApiResponse<AdminAppListResponse> appList() {
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        return new ApiResponse<>(new AdminAppListResponse(merchantCode));
    }

}
